# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import MySQLdb
import scrapy
from scrapy.contrib.pipeline.images import ImagesPipeline
from scrapy.exceptions import DropItem


class MoviesPipeline(object):

    def __init__(self):
        self.conn = MySQLdb.connect(host='127.0.0.1',
                                    port=3306,
                                    user='root',
                                    passwd='root',
                                    db='movies',
                                    charset='utf8'
                                    )
        self.cursor = self.conn.cursor()
        #self.cursor.execute("truncate table dytt8")
        self.conn.commit()

    def process_item(self, item, spider):

        for key in item:
            if not item[key]:
                item[key] = "NA"
            else:
                item[key] = item[key][0].strip().replace("<br>",",")

        insert_cmd = "insert into dytt8 (movie_summary, movie_name, movie_release_year, movie_release_year_more, " \
                     "movie_place, movie_language, movie_duration, movie_score, movie_guide, movie_actors, " \
                     "movie_download_url_ftp) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"

        data = (item["movie_summary"], item["movie_name"], item["movie_release_year"], item["movie_release_year_more"],
                item["movie_place"], item["movie_language"], item["movie_duration"], item["movie_score"],
                item["movie_guide"], item["movie_actors"], item["movie_download_url_ftp"])

        try:
            self.cursor.execute(insert_cmd, data)
            self.conn.commit()
        except Exception,e:
            print(Exception,e)

        return item

    def fun_plus(self, p_key):
        sql_cmd = "select exists(select 1 from dytt8 where movie_summary=%(p_key)s"
        value = {"p_key": p_key}
        self.cursor.execute(sql_cmd, value)
        return self.cursor.fetchall()[0]



